don't enable serialization caching by default
[p2pool.git] / p2pool / bitcoin / data.py
1 from __future__ import division
2
3 import hashlib
4 import struct
5
6 from . import base58
7 from p2pool.util import bases, math, expiring_dict, memoize, slush
8 import p2pool
9
10 class EarlyEnd(Exception):
11     pass
12
13 class LateEnd(Exception):
14     pass
15
16 def read((data, pos), length):
17     data2 = data[pos:pos + length]
18     if len(data2) != length:
19         raise EarlyEnd()
20     return data2, (data, pos + length)
21
22 def size((data, pos)):
23     return len(data) - pos
24
25 class Type(object):
26     # the same data can have only one unpacked representation, but multiple packed binary representations
27     
28     def __hash__(self):
29         rval = getattr(self, '_hash', None)
30         if rval is None:
31             try:
32                 rval = self._hash = hash((type(self), frozenset(self.__dict__.items())))
33             except:
34                 print self.__dict__
35                 raise
36         return rval
37     
38     def __eq__(self, other):
39         return type(other) is type(self) and other.__dict__ == self.__dict__
40     
41     def __ne__(self, other):
42         return not (self == other)
43     
44     def _unpack(self, data):
45         obj, (data2, pos) = self.read((data, 0))
46         
47         assert data2 is data
48         
49         if pos != len(data):
50             raise LateEnd()
51         
52         return obj
53     
54     def _pack(self, obj):
55         f = self.write(None, obj)
56         
57         res = []
58         while f is not None:
59             res.append(f[1])
60             f = f[0]
61         res.reverse()
62         return ''.join(res)
63     
64     
65     def unpack(self, data):
66         obj = self._unpack(data)
67         
68         if p2pool.DEBUG:
69             data2 = self._pack(obj)
70             if data2 != data:
71                 if self._unpack(data2) != obj:
72                     raise AssertionError()
73         
74         return obj
75     
76     def pack2(self, obj):
77         data = self._pack(obj)
78         
79         if p2pool.DEBUG:
80             if self._unpack(data) != obj:
81                 raise AssertionError((self._unpack(data), obj))
82         
83         return data
84     
85     _backing = None
86     
87     @classmethod
88     def enable_caching(cls):
89         assert cls._backing is None
90         cls._backing = expiring_dict.ExpiringDict(100)
91         cls._pre_pack2 = cls.pack2
92         cls.pack2 = memoize.memoize_with_backing(cls._backing, [cls.unpack])(cls.pack2)
93         cls._pre_unpack = cls.unpack
94         cls.unpack = memoize.memoize_with_backing(cls._backing)(cls.unpack) # doesn't have an inverse
95     
96     @classmethod
97     def disable_caching(cls):
98         assert cls._backing is not None
99         cls._backing.stop()
100         cls._backing = None
101         cls.pack2 = cls._pre_pack2
102         del cls._pre_pack2
103         cls.unpack = cls._pre_unpack
104         del cls._pre_unpack
105     
106     def pack(self, obj):
107         return self.pack2(slush.immutify(obj))
108     
109     
110     def pack_base58(self, obj):
111         return base58.base58_encode(self.pack(obj))
112     
113     def unpack_base58(self, base58_data):
114         return self.unpack(base58.base58_decode(base58_data))
115     
116     
117     def hash160(self, obj):
118         return ShortHashType().unpack(hashlib.new('ripemd160', hashlib.sha256(self.pack(obj)).digest()).digest())
119     
120     def hash256(self, obj):
121         return HashType().unpack(hashlib.sha256(hashlib.sha256(self.pack(obj)).digest()).digest())
122     
123     def scrypt(self, obj):
124         import ltc_scrypt
125         return HashType().unpack(ltc_scrypt.getPoWHash(self.pack(obj)))
126
127 class VarIntType(Type):
128     # redundancy doesn't matter here because bitcoin and p2pool both reencode before hashing
129     def read(self, file):
130         data, file = read(file, 1)
131         first = ord(data)
132         if first < 0xfd:
133             return first, file
134         elif first == 0xfd:
135             desc, length = '<H', 2
136         elif first == 0xfe:
137             desc, length = '<I', 4
138         elif first == 0xff:
139             desc, length = '<Q', 8
140         else:
141             raise AssertionError()
142         data, file = read(file, length)
143         return struct.unpack(desc, data)[0], file
144     
145     def write(self, file, item):
146         if item < 0xfd:
147             file = file, struct.pack('<B', item)
148         elif item <= 0xffff:
149             file = file, struct.pack('<BH', 0xfd, item)
150         elif item <= 0xffffffff:
151             file = file, struct.pack('<BI', 0xfe, item)
152         elif item <= 0xffffffffffffffff:
153             file = file, struct.pack('<BQ', 0xff, item)
154         else:
155             raise ValueError('int too large for varint')
156         return file
157
158 class VarStrType(Type):
159     _inner_size = VarIntType()
160     
161     def read(self, file):
162         length, file = self._inner_size.read(file)
163         return read(file, length)
164     
165     def write(self, file, item):
166         return self._inner_size.write(file, len(item)), item
167
168 class FixedStrType(Type):
169     def __init__(self, length):
170         self.length = length
171     
172     def read(self, file):
173         return read(file, self.length)
174     
175     def write(self, file, item):
176         if len(item) != self.length:
177             raise ValueError('incorrect length item!')
178         return file, item
179
180 class EnumType(Type):
181     def __init__(self, inner, values):
182         self.inner = inner
183         self.values = slush.frozendict(values)
184         
185         keys = {}
186         for k, v in values.iteritems():
187             if v in keys:
188                 raise ValueError('duplicate value in values')
189             keys[v] = k
190         self.keys = slush.frozendict(keys)
191     
192     def read(self, file):
193         data, file = self.inner.read(file)
194         if data not in self.keys:
195             raise ValueError('enum data (%r) not in values (%r)' % (data, self.values))
196         return self.keys[data], file
197     
198     def write(self, file, item):
199         if item not in self.values:
200             raise ValueError('enum item (%r) not in values (%r)' % (item, self.values))
201         return self.inner.write(file, self.values[item])
202
203 class HashType(Type):
204     def read(self, file):
205         data, file = read(file, 256//8)
206         return int(data[::-1].encode('hex'), 16), file
207     
208     def write(self, file, item):
209         if not 0 <= item < 2**256:
210             raise ValueError('invalid hash value - %r' % (item,))
211         if item != 0 and item < 2**160:
212             print 'Very low hash value - maybe you meant to use ShortHashType? %x' % (item,)
213         return file, ('%064x' % (item,)).decode('hex')[::-1]
214
215 class ShortHashType(Type):
216     def read(self, file):
217         data, file = read(file, 160//8)
218         return int(data[::-1].encode('hex'), 16), file
219     
220     def write(self, file, item):
221         if not 0 <= item < 2**160:
222             raise ValueError('invalid hash value - %r' % (item,))
223         return file, ('%040x' % (item,)).decode('hex')[::-1]
224
225 class ListType(Type):
226     _inner_size = VarIntType()
227     
228     def __init__(self, type):
229         self.type = type
230     
231     def read(self, file):
232         length, file = self._inner_size.read(file)
233         res = []
234         for i in xrange(length):
235             item, file = self.type.read(file)
236             res.append(item)
237         return res, file
238     
239     def write(self, file, item):
240         file = self._inner_size.write(file, len(item))
241         for subitem in item:
242             file = self.type.write(file, subitem)
243         return file
244
245 class StructType(Type):
246     def __init__(self, desc):
247         self.desc = desc
248         self.length = struct.calcsize(self.desc)
249     
250     def read(self, file):
251         data, file = read(file, self.length)
252         res, = struct.unpack(self.desc, data)
253         return res, file
254     
255     def write(self, file, item):
256         data = struct.pack(self.desc, item)
257         if struct.unpack(self.desc, data)[0] != item:
258             # special test because struct doesn't error on some overflows
259             raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
260         return file, data
261
262 class IPV6AddressType(Type):
263     def read(self, file):
264         data, file = read(file, 16)
265         if data[:12] != '00000000000000000000ffff'.decode('hex'):
266             raise ValueError('ipv6 addresses not supported yet')
267         return '.'.join(str(ord(x)) for x in data[12:]), file
268     
269     def write(self, file, item):
270         bits = map(int, item.split('.'))
271         if len(bits) != 4:
272             raise ValueError('invalid address: %r' % (bits,))
273         data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
274         assert len(data) == 16, len(data)
275         return file, data
276
277 _record_types = {}
278
279 def get_record(fields):
280     fields = tuple(sorted(fields))
281     if 'keys' in fields:
282         raise ValueError()
283     if fields not in _record_types:
284         class _Record(object):
285             __slots__ = fields
286             def __repr__(self):
287                 return repr(dict(self))
288             def __getitem__(self, key):
289                 return getattr(self, key)
290             def __setitem__(self, key, value):
291                 setattr(self, key, value)
292             #def __iter__(self):
293             #    for field in self.__slots__:
294             #        yield field, getattr(self, field)
295             def keys(self):
296                 return self.__slots__
297             def __eq__(self, other):
298                 if isinstance(other, dict):
299                     return dict(self) == other
300                 elif isinstance(other, _Record):
301                     return all(self[k] == other[k] for k in self.keys())
302                 raise TypeError()
303             def __ne__(self, other):
304                 return not (self == other)
305         _record_types[fields] = _Record
306     return _record_types[fields]()
307
308 class ComposedType(Type):
309     def __init__(self, fields):
310         self.fields = tuple(fields)
311     
312     def read(self, file):
313         item = get_record(k for k, v in self.fields)
314         for key, type_ in self.fields:
315             item[key], file = type_.read(file)
316         return item, file
317     
318     def write(self, file, item):
319         for key, type_ in self.fields:
320             file = type_.write(file, item[key])
321         return file
322
323 class ChecksummedType(Type):
324     def __init__(self, inner):
325         self.inner = inner
326     
327     def read(self, file):
328         obj, file = self.inner.read(file)
329         data = self.inner.pack(obj)
330         
331         checksum, file = read(file, 4)
332         if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
333             raise ValueError('invalid checksum')
334         
335         return obj, file
336     
337     def write(self, file, item):
338         data = self.inner.pack(item)
339         return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
340
341 class FloatingInteger(object):
342     __slots__ = ['bits', '_target']
343     
344     @classmethod
345     def from_target_upper_bound(cls, target):
346         n = bases.natural_to_string(target)
347         if n and ord(n[0]) >= 128:
348             n = '\x00' + n
349         bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
350         bits = struct.unpack('<I', bits2)[0]
351         return cls(bits)
352     
353     def __init__(self, bits, target=None):
354         self.bits = bits
355         self._target = None
356         if target is not None and self.target != target:
357             raise ValueError('target does not match')
358     
359     @property
360     def target(self):
361         res = self._target
362         if res is None:
363             res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
364         return res
365     
366     def __hash__(self):
367         return hash(self.bits)
368     
369     def __eq__(self, other):
370         return self.bits == other.bits
371     
372     def __ne__(self, other):
373         return not (self == other)
374     
375     def __cmp__(self, other):
376         assert False
377     
378     def __repr__(self):
379         return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
380
381 class FloatingIntegerType(Type):
382     _inner = StructType('<I')
383     
384     def read(self, file):
385         bits, file = self._inner.read(file)
386         return FloatingInteger(bits), file
387     
388     def write(self, file, item):
389         return self._inner.write(file, item.bits)
390
391 class PossiblyNoneType(Type):
392     def __init__(self, none_value, inner):
393         self.none_value = none_value
394         self.inner = inner
395     
396     def read(self, file):
397         value, file = self.inner.read(file)
398         return None if value == self.none_value else value, file
399     
400     def write(self, file, item):
401         if item == self.none_value:
402             raise ValueError('none_value used')
403         return self.inner.write(file, self.none_value if item is None else item)
404
405 address_type = ComposedType([
406     ('services', StructType('<Q')),
407     ('address', IPV6AddressType()),
408     ('port', StructType('>H')),
409 ])
410
411 tx_type = ComposedType([
412     ('version', StructType('<I')),
413     ('tx_ins', ListType(ComposedType([
414         ('previous_output', PossiblyNoneType(slush.frozendict(hash=0, index=2**32 - 1), ComposedType([
415             ('hash', HashType()),
416             ('index', StructType('<I')),
417         ]))),
418         ('script', VarStrType()),
419         ('sequence', PossiblyNoneType(2**32 - 1, StructType('<I'))),
420     ]))),
421     ('tx_outs', ListType(ComposedType([
422         ('value', StructType('<Q')),
423         ('script', VarStrType()),
424     ]))),
425     ('lock_time', StructType('<I')),
426 ])
427
428 merkle_branch_type = ListType(HashType())
429
430 merkle_tx_type = ComposedType([
431     ('tx', tx_type),
432     ('block_hash', HashType()),
433     ('merkle_branch', merkle_branch_type),
434     ('index', StructType('<i')),
435 ])
436
437 block_header_type = ComposedType([
438     ('version', StructType('<I')),
439     ('previous_block', PossiblyNoneType(0, HashType())),
440     ('merkle_root', HashType()),
441     ('timestamp', StructType('<I')),
442     ('bits', FloatingIntegerType()),
443     ('nonce', StructType('<I')),
444 ])
445
446 block_type = ComposedType([
447     ('header', block_header_type),
448     ('txs', ListType(tx_type)),
449 ])
450
451 aux_pow_type = ComposedType([
452     ('merkle_tx', merkle_tx_type),
453     ('merkle_branch', merkle_branch_type),
454     ('index', StructType('<i')),
455     ('parent_block_header', block_header_type),
456 ])
457
458
459 merkle_record_type = ComposedType([
460     ('left', HashType()),
461     ('right', HashType()),
462 ])
463
464 def merkle_hash(hashes):
465     if not hashes:
466         return 0
467     hash_list = list(hashes)
468     while len(hash_list) > 1:
469         hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
470             for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
471     return hash_list[0]
472
473 def calculate_merkle_branch(hashes, index):
474     # XXX optimize this
475     
476     hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
477     
478     while len(hash_list) > 1:
479         hash_list = [
480             (
481                 merkle_record_type.hash256(dict(left=left, right=right)),
482                 left_f or right_f,
483                 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
484             )
485             for (left, left_f, left_l), (right, right_f, right_l) in
486                 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
487         ]
488     
489     res = [x['hash'] for x in hash_list[0][2]]
490     
491     assert hash_list[0][1]
492     assert check_merkle_branch(hashes[index], index, res) == hash_list[0][0]
493     assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
494     
495     return res
496
497 def check_merkle_branch(tip_hash, index, merkle_branch):
498     return reduce(lambda c, (i, h): merkle_record_type.hash256(
499         dict(left=h, right=c) if 2**i & index else
500         dict(left=c, right=h)
501     ), enumerate(merkle_branch), tip_hash)
502
503 def target_to_average_attempts(target):
504     return 2**256//(target + 1)
505
506 def target_to_difficulty(target):
507     return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
508
509 # tx
510
511 def tx_get_sigop_count(tx):
512     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'])
513
514 # human addresses
515
516 human_address_type = ChecksummedType(ComposedType([
517     ('version', StructType('<B')),
518     ('pubkey_hash', ShortHashType()),
519 ]))
520
521 pubkey_type = FixedStrType(65)
522
523 def pubkey_hash_to_address(pubkey_hash, net):
524     return human_address_type.pack_base58(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash))
525
526 def pubkey_to_address(pubkey, net):
527     return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
528
529 def address_to_pubkey_hash(address, net):
530     x = human_address_type.unpack_base58(address)
531     if x['version'] != net.ADDRESS_VERSION:
532         raise ValueError('address not for this net!')
533     return x['pubkey_hash']
534
535 # transactions
536
537 def pubkey_to_script2(pubkey):
538     return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
539
540 def pubkey_hash_to_script2(pubkey_hash):
541     return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
542
543 def script2_to_human(script2, net):
544     try:
545         pubkey = script2[1:-1]
546         script2_test = pubkey_to_script2(pubkey)
547     except:
548         pass
549     else:
550         if script2_test == script2:
551             return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
552     
553     try:
554         pubkey_hash = ShortHashType().unpack(script2[3:-2])
555         script2_test2 = pubkey_hash_to_script2(pubkey_hash)
556     except:
557         pass
558     else:
559         if script2_test2 == script2:
560             return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
561     
562     return 'Unknown. Script: %s'  % (script2.encode('hex'),)