FrozenList to reduce memory usage
[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 FrozenList(tuple):
186     def __eq__(self, other):
187         if isinstance(other, FrozenList):
188             return tuple.__eq__(self, other)
189         elif isinstance(other, list):
190             return len(self) == len(other) and all(a == b for a, b in itertools.izip(self, other))
191         else:
192             raise TypeError()
193     def __ne__(self, other):
194         return not (self == other)
195
196 class ListType(Type):
197     _inner_size = VarIntType()
198     
199     def __init__(self, type):
200         self.type = type
201     
202     def read(self, file):
203         length, file = self._inner_size.read(file)
204         res = []
205         for i in xrange(length):
206             item, file = self.type.read(file)
207             res.append(item)
208         return FrozenList(res), file
209     
210     def write(self, file, item):
211         file = self._inner_size.write(file, len(item))
212         for subitem in item:
213             file = self.type.write(file, subitem)
214         return file
215
216 class StructType(Type):
217     def __init__(self, desc):
218         self.desc = desc
219         self.length = struct.calcsize(self.desc)
220     
221     def read(self, file):
222         data, file = read(file, self.length)
223         res, = struct.unpack(self.desc, data)
224         return res, file
225     
226     def write(self, file, item):
227         data = struct.pack(self.desc, item)
228         if struct.unpack(self.desc, data)[0] != item:
229             # special test because struct doesn't error on some overflows
230             raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
231         return file, data
232
233 class IPV6AddressType(Type):
234     def read(self, file):
235         data, file = read(file, 16)
236         if data[:12] != '00000000000000000000ffff'.decode('hex'):
237             raise ValueError('ipv6 addresses not supported yet')
238         return '.'.join(str(ord(x)) for x in data[12:]), file
239     
240     def write(self, file, item):
241         bits = map(int, item.split('.'))
242         if len(bits) != 4:
243             raise ValueError('invalid address: %r' % (bits,))
244         data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
245         assert len(data) == 16, len(data)
246         return file, data
247
248 _record_types = {}
249
250 def get_record(fields):
251     fields = tuple(sorted(fields))
252     if 'keys' in fields:
253         raise ValueError()
254     if fields not in _record_types:
255         class _Record(object):
256             __slots__ = fields
257             def __getitem__(self, key):
258                 return getattr(self, key)
259             def __setitem__(self, key, value):
260                 setattr(self, key, value)
261             #def __iter__(self):
262             #    for field in self.__slots__:
263             #        yield field, getattr(self, field)
264             def keys(self):
265                 return self.__slots__
266             def __eq__(self, other):
267                 if isinstance(other, dict):
268                     return dict(self) == other
269                 elif isinstance(other, _Record):
270                     return all(self[k] == other[k] for k in self.keys())
271                 raise TypeError()
272             def __ne__(self, other):
273                 return not (self == other)
274         _record_types[fields] = _Record
275     return _record_types[fields]()
276
277 class ComposedType(Type):
278     def __init__(self, fields):
279         self.fields = fields
280     
281     def read(self, file):
282         item = get_record(k for k, v in self.fields)
283         for key, type_ in self.fields:
284             item[key], file = type_.read(file)
285         return item, file
286     
287     def write(self, file, item):
288         for key, type_ in self.fields:
289             file = type_.write(file, item[key])
290         return file
291
292 class ChecksummedType(Type):
293     def __init__(self, inner):
294         self.inner = inner
295     
296     def read(self, file):
297         obj, file = self.inner.read(file)
298         data = self.inner.pack(obj)
299         
300         checksum, file = read(file, 4)
301         if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
302             raise ValueError('invalid checksum')
303         
304         return obj, file
305     
306     def write(self, file, item):
307         data = self.inner.pack(item)
308         return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
309
310 class FloatingIntegerType(Type):
311     # redundancy doesn't matter here because bitcoin checks binary bits against its own computed bits
312     # so it will always be encoded 'normally' in blocks (they way bitcoin does it)
313     _inner = StructType('<I')
314     
315     def read(self, file):
316         bits, file = self._inner.read(file)
317         target = self._bits_to_target(bits)
318         if p2pool.DEBUG:
319             if self._target_to_bits(target) != bits:
320                 raise ValueError('bits in non-canonical form')
321         return target, file
322     
323     def write(self, file, item):
324         return self._inner.write(file, self._target_to_bits(item))
325     
326     def truncate_to(self, x):
327         return self._bits_to_target(self._target_to_bits(x, _check=False))
328     
329     def _bits_to_target(self, bits2):
330         target = math.shift_left(bits2 & 0x00ffffff, 8 * ((bits2 >> 24) - 3))
331         if p2pool.DEBUG:
332             assert target == self._bits_to_target1(struct.pack('<I', bits2))
333             assert self._target_to_bits(target, _check=False) == bits2
334         return target
335     
336     def _bits_to_target1(self, bits):
337         bits = bits[::-1]
338         length = ord(bits[0])
339         return bases.string_to_natural((bits[1:] + '\0'*length)[:length])
340     
341     def _target_to_bits(self, target, _check=True):
342         n = bases.natural_to_string(target)
343         if n and ord(n[0]) >= 128:
344             n = '\x00' + n
345         bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
346         bits = struct.unpack('<I', bits2)[0]
347         if _check:
348             if self._bits_to_target(bits) != target:
349                 raise ValueError(repr((target, self._bits_to_target(bits, _check=False))))
350         return bits
351
352 class PossiblyNone(Type):
353     def __init__(self, none_value, inner):
354         self.none_value = none_value
355         self.inner = inner
356     
357     def read(self, file):
358         value, file = self.inner.read(file)
359         return None if value == self.none_value else value, file
360     
361     def write(self, file, item):
362         if item == self.none_value:
363             raise ValueError('none_value used')
364         return self.inner.write(file, self.none_value if item is None else item)
365
366 address_type = ComposedType([
367     ('services', StructType('<Q')),
368     ('address', IPV6AddressType()),
369     ('port', StructType('>H')),
370 ])
371
372 tx_type = ComposedType([
373     ('version', StructType('<I')),
374     ('tx_ins', ListType(ComposedType([
375         ('previous_output', PossiblyNone(dict(hash=0, index=2**32 - 1), ComposedType([
376             ('hash', HashType()),
377             ('index', StructType('<I')),
378         ]))),
379         ('script', VarStrType()),
380         ('sequence', PossiblyNone(2**32 - 1, StructType('<I'))),
381     ]))),
382     ('tx_outs', ListType(ComposedType([
383         ('value', StructType('<Q')),
384         ('script', VarStrType()),
385     ]))),
386     ('lock_time', StructType('<I')),
387 ])
388
389 block_header_type = ComposedType([
390     ('version', StructType('<I')),
391     ('previous_block', PossiblyNone(0, HashType())),
392     ('merkle_root', HashType()),
393     ('timestamp', StructType('<I')),
394     ('target', FloatingIntegerType()),
395     ('nonce', StructType('<I')),
396 ])
397
398 block_type = ComposedType([
399     ('header', block_header_type),
400     ('txs', ListType(tx_type)),
401 ])
402
403
404 merkle_record_type = ComposedType([
405     ('left', HashType()),
406     ('right', HashType()),
407 ])
408
409 def merkle_hash(tx_list):
410     if not tx_list:
411         return 0
412     hash_list = map(tx_type.hash256, tx_list)
413     while len(hash_list) > 1:
414         hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
415             for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
416     return hash_list[0]
417
418 def target_to_average_attempts(target):
419     return 2**256//(target + 1)
420
421 # tx
422
423 def tx_get_sigop_count(tx):
424     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'])
425
426 # human addresses
427
428 human_address_type = ChecksummedType(ComposedType([
429     ('version', StructType('<B')),
430     ('pubkey_hash', ShortHashType()),
431 ]))
432
433 pubkey_type = FixedStrType(65)
434
435 def pubkey_hash_to_address(pubkey_hash, net):
436     return human_address_type.pack_base58(dict(version=net.BITCOIN_ADDRESS_VERSION, pubkey_hash=pubkey_hash))
437
438 def pubkey_to_address(pubkey, net):
439     return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
440
441 def address_to_pubkey_hash(address, net):
442     x = human_address_type.unpack_base58(address)
443     if x['version'] != net.BITCOIN_ADDRESS_VERSION:
444         raise ValueError('address not for this net!')
445     return x['pubkey_hash']
446
447 # transactions
448
449 def pubkey_to_script2(pubkey):
450     return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
451
452 def pubkey_hash_to_script2(pubkey_hash):
453     return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
454
455 # linked list tracker
456
457 class Tracker(object):
458     def __init__(self):
459         self.shares = {} # hash -> share
460         #self.ids = {} # hash -> (id, height)
461         self.reverse_shares = {} # previous_hash -> set of share_hashes
462         
463         self.heads = {} # head hash -> tail_hash
464         self.tails = {} # tail hash -> set of head hashes
465         
466         self.heights = {} # share_hash -> height_to, other_share_hash
467         
468         '''
469         self.id_generator = itertools.count()
470         self.tails_by_id = {}
471         '''
472         
473         self.get_nth_parent_hash = skiplists.DistanceSkipList(self)
474     
475     def add(self, share):
476         assert not isinstance(share, (int, long, type(None)))
477         if share.hash in self.shares:
478             return # XXX raise exception?
479         
480         '''
481         parent_id = self.ids.get(share.previous_hash, None)
482         children_ids = set(self.ids.get(share2_hash) for share2_hash in self.reverse_shares.get(share.hash, set()))
483         infos = set()
484         if parent_id is not None:
485             infos.add((parent_id[0], parent_id[1] + 1))
486         for child_id in children_ids:
487             infos.add((child_id[0], child_id[1] - 1))
488         if not infos:
489             infos.add((self.id_generator.next(), 0))
490         chosen = min(infos)
491         self.ids[share.hash] = chosen
492         '''
493         
494         self.shares[share.hash] = share
495         self.reverse_shares.setdefault(share.previous_hash, set()).add(share.hash)
496         
497         if share.hash in self.tails:
498             heads = self.tails.pop(share.hash)
499         else:
500             heads = set([share.hash])
501         
502         if share.previous_hash in self.heads:
503             tail = self.heads.pop(share.previous_hash)
504         else:
505             #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
506             tail = share.previous_hash
507             while tail in self.shares:
508                 tail = self.shares[tail].previous_hash
509         
510         self.tails.setdefault(tail, set()).update(heads)
511         if share.previous_hash in self.tails[tail]:
512             self.tails[tail].remove(share.previous_hash)
513         
514         for head in heads:
515             self.heads[head] = tail
516     
517     def test(self):
518         t = Tracker()
519         for s in self.shares.itervalues():
520             t.add(s)
521         
522         assert self.shares == t.shares, (self.shares, t.shares)
523         assert self.reverse_shares == t.reverse_shares, (self.reverse_shares, t.reverse_shares)
524         assert self.heads == t.heads, (self.heads, t.heads)
525         assert self.tails == t.tails, (self.tails, t.tails)
526     
527     def remove(self, share_hash):
528         assert isinstance(share_hash, (int, long, type(None)))
529         if share_hash not in self.shares:
530             raise KeyError()
531         share = self.shares[share_hash]
532         del share_hash
533         
534         if share.hash in self.heads and share.previous_hash in self.tails:
535             tail = self.heads.pop(share.hash)
536             self.tails[tail].remove(share.hash)
537             if not self.tails[share.previous_hash]:
538                 self.tails.pop(share.previous_hash)
539         elif share.hash in self.heads:
540             tail = self.heads.pop(share.hash)
541             self.tails[tail].remove(share.hash)
542             if self.reverse_shares[share.previous_hash] != set([share.hash]):
543                 pass # has sibling
544             else:
545                 self.tails[tail].add(share.previous_hash)
546                 self.heads[share.previous_hash] = tail
547         elif share.previous_hash in self.tails:
548             raise NotImplementedError() # will break other things..
549             heads = self.tails[share.previous_hash]
550             if len(self.reverse_shares[share.previous_hash]) > 1:
551                 raise NotImplementedError()
552             else:
553                 del self.tails[share.previous_hash]
554                 for head in heads:
555                     self.heads[head] = share.hash
556                 self.tails[share.hash] = set(heads)
557         else:
558             raise NotImplementedError()
559         
560         '''
561         height, tail = self.get_height_and_last(share.hash)
562         
563         if share.hash in self.heads:
564             my_heads = set([share.hash])
565         elif share.previous_hash in self.tails:
566             my_heads = self.tails[share.previous_hash]
567         else:
568             some_heads = self.tails[tail]
569             some_heads_heights = dict((that_head, self.get_height_and_last(that_head)[0]) for that_head in some_heads)
570             my_heads = set(that_head for that_head in some_heads
571                 if some_heads_heights[that_head] > height and
572                 self.get_nth_parent_hash(that_head, some_heads_heights[that_head] - height) == share.hash)
573         
574         if share.previous_hash != tail:
575             self.heads[share.previous_hash] = tail
576         
577         for head in my_heads:
578             if head != share.hash:
579                 self.heads[head] = share.hash
580             else:
581                 self.heads.pop(head)
582         
583         if share.hash in self.heads:
584             self.heads.pop(share.hash)
585         
586         
587         self.tails[tail].difference_update(my_heads)
588         if share.previous_hash != tail:
589             self.tails[tail].add(share.previous_hash)
590         if not self.tails[tail]:
591             self.tails.pop(tail)
592         if my_heads != set([share.hash]):
593             self.tails[share.hash] = set(my_heads) - set([share.hash])
594         '''
595         
596         self.shares.pop(share.hash)
597         self.reverse_shares[share.previous_hash].remove(share.hash)
598         if not self.reverse_shares[share.previous_hash]:
599             self.reverse_shares.pop(share.previous_hash)
600         
601         #assert self.test() is None
602     
603     def get_height(self, share_hash):
604         height, work, last = self.get_height_work_and_last(share_hash)
605         return height
606     
607     def get_work(self, share_hash):
608         height, work, last = self.get_height_work_and_last(share_hash)
609         return work
610     
611     def get_height_and_last(self, share_hash):
612         height, work, last = self.get_height_work_and_last(share_hash)
613         return height, last
614     
615     def get_height_work_and_last(self, share_hash):
616         assert isinstance(share_hash, (int, long, type(None)))
617         orig = share_hash
618         height = 0
619         work = 0
620         updates = []
621         while True:
622             if share_hash is None or share_hash not in self.shares:
623                 break
624             updates.append((share_hash, height, work))
625             if share_hash in self.heights:
626                 height_inc, share_hash, work_inc = self.heights[share_hash]
627             else:
628                 height_inc, share_hash, work_inc = 1, self.shares[share_hash].previous_hash, target_to_average_attempts(self.shares[share_hash].target)
629             height += height_inc
630             work += work_inc
631         for update_hash, height_then, work_then in updates:
632             self.heights[update_hash] = height - height_then, share_hash, work - work_then
633         return height, work, share_hash
634     
635     def get_chain_known(self, start_hash):
636         assert isinstance(start_hash, (int, long, type(None)))
637         '''
638         Chain starting with item of hash I{start_hash} of items that this Tracker contains
639         '''
640         item_hash_to_get = start_hash
641         while True:
642             if item_hash_to_get not in self.shares:
643                 break
644             share = self.shares[item_hash_to_get]
645             assert not isinstance(share, long)
646             yield share
647             item_hash_to_get = share.previous_hash
648     
649     def get_chain_to_root(self, start_hash, root=None):
650         assert isinstance(start_hash, (int, long, type(None)))
651         assert isinstance(root, (int, long, type(None)))
652         '''
653         Chain of hashes starting with share_hash of shares to the root (doesn't include root)
654         Raises an error if one is missing
655         '''
656         share_hash_to_get = start_hash
657         while share_hash_to_get != root:
658             share = self.shares[share_hash_to_get]
659             yield share
660             share_hash_to_get = share.previous_hash
661     
662     def get_best_hash(self):
663         '''
664         Returns hash of item with the most items in its chain
665         '''
666         if not self.heads:
667             return None
668         return max(self.heads, key=self.get_height_and_last)
669     
670     def get_highest_height(self):
671         return max(self.get_height_and_last(head)[0] for head in self.heads) if self.heads else 0
672
673 class FakeShare(object):
674     def __init__(self, **kwargs):
675         self.__dict__.update(kwargs)
676
677 if __name__ == '__main__':
678     
679     t = Tracker()
680     
681     for i in xrange(10000):
682         t.add(FakeShare(hash=i, previous_hash=i - 1 if i > 0 else None))
683     
684     #t.remove(99)
685     
686     print 'HEADS', t.heads
687     print 'TAILS', t.tails
688     
689     import random
690     
691     while False:
692         print
693         print '-'*30
694         print
695         t = Tracker()
696         for i in xrange(random.randrange(100)):
697             x = random.choice(list(t.shares) + [None])
698             print i, '->', x
699             t.add(FakeShare(i, x))
700         while t.shares:
701             x = random.choice(list(t.shares))
702             print 'DEL', x, t.__dict__
703             try:
704                 t.remove(x)
705             except NotImplementedError:
706                 print 'aborted; not implemented'
707         import time
708         time.sleep(.1)
709         print 'HEADS', t.heads
710         print 'TAILS', t.tails
711     
712     #for share_hash, share in sorted(t.shares.iteritems()):
713     #    print share_hash, share.previous_hash, t.heads.get(share_hash), t.tails.get(share_hash)
714     
715     #import sys;sys.exit()
716     
717     print t.get_nth_parent_hash(9000, 5000)
718     print t.get_nth_parent_hash(9001, 412)
719     #print t.get_nth_parent_hash(90, 51)
720     
721     for share_hash in sorted(t.shares):
722         print str(share_hash).rjust(4),
723         x = t.skips.get(share_hash, None)
724         if x is not None:
725             print str(x[0]).rjust(4),
726             for a in x[1]:
727                 print str(a).rjust(10),
728         print
729
730 # network definitions
731
732 class Mainnet(object):
733     BITCOIN_P2P_PREFIX = 'f9beb4d9'.decode('hex')
734     BITCOIN_P2P_PORT = 8333
735     BITCOIN_ADDRESS_VERSION = 0
736
737 class Testnet(object):
738     BITCOIN_P2P_PREFIX = 'fabfb5da'.decode('hex')
739     BITCOIN_P2P_PORT = 18333
740     BITCOIN_ADDRESS_VERSION = 111