removed checkorder, submit order Bitcoin p2p messages and FixedStrType
[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.encode(self.pack(obj))
112     
113     def unpack_base58(self, base58_data):
114         return self.unpack(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 PassthruType(Type):
169     def read(self, file):
170         return read(file, size(file))
171     
172     def write(self, file, item):
173         return file, item
174
175 class EnumType(Type):
176     def __init__(self, inner, values):
177         self.inner = inner
178         self.values = slush.frozendict(values)
179         
180         keys = {}
181         for k, v in values.iteritems():
182             if v in keys:
183                 raise ValueError('duplicate value in values')
184             keys[v] = k
185         self.keys = slush.frozendict(keys)
186     
187     def read(self, file):
188         data, file = self.inner.read(file)
189         if data not in self.keys:
190             raise ValueError('enum data (%r) not in values (%r)' % (data, self.values))
191         return self.keys[data], file
192     
193     def write(self, file, item):
194         if item not in self.values:
195             raise ValueError('enum item (%r) not in values (%r)' % (item, self.values))
196         return self.inner.write(file, self.values[item])
197
198 class HashType(Type):
199     def read(self, file):
200         data, file = read(file, 256//8)
201         return int(data[::-1].encode('hex'), 16), file
202     
203     def write(self, file, item):
204         if not 0 <= item < 2**256:
205             raise ValueError('invalid hash value - %r' % (item,))
206         if item != 0 and item < 2**160:
207             print 'Very low hash value - maybe you meant to use ShortHashType? %x' % (item,)
208         return file, ('%064x' % (item,)).decode('hex')[::-1]
209
210 class ShortHashType(Type):
211     def read(self, file):
212         data, file = read(file, 160//8)
213         return int(data[::-1].encode('hex'), 16), file
214     
215     def write(self, file, item):
216         if not 0 <= item < 2**160:
217             raise ValueError('invalid hash value - %r' % (item,))
218         return file, ('%040x' % (item,)).decode('hex')[::-1]
219
220 class ListType(Type):
221     _inner_size = VarIntType()
222     
223     def __init__(self, type):
224         self.type = type
225     
226     def read(self, file):
227         length, file = self._inner_size.read(file)
228         res = []
229         for i in xrange(length):
230             item, file = self.type.read(file)
231             res.append(item)
232         return res, file
233     
234     def write(self, file, item):
235         file = self._inner_size.write(file, len(item))
236         for subitem in item:
237             file = self.type.write(file, subitem)
238         return file
239
240 class StructType(Type):
241     def __init__(self, desc):
242         self.desc = desc
243         self.length = struct.calcsize(self.desc)
244     
245     def read(self, file):
246         data, file = read(file, self.length)
247         res, = struct.unpack(self.desc, data)
248         return res, file
249     
250     def write(self, file, item):
251         data = struct.pack(self.desc, item)
252         if struct.unpack(self.desc, data)[0] != item:
253             # special test because struct doesn't error on some overflows
254             raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
255         return file, data
256
257 class IPV6AddressType(Type):
258     def read(self, file):
259         data, file = read(file, 16)
260         if data[:12] != '00000000000000000000ffff'.decode('hex'):
261             raise ValueError('ipv6 addresses not supported yet')
262         return '.'.join(str(ord(x)) for x in data[12:]), file
263     
264     def write(self, file, item):
265         bits = map(int, item.split('.'))
266         if len(bits) != 4:
267             raise ValueError('invalid address: %r' % (bits,))
268         data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
269         assert len(data) == 16, len(data)
270         return file, data
271
272 _record_types = {}
273
274 def get_record(fields):
275     fields = tuple(sorted(fields))
276     if 'keys' in fields:
277         raise ValueError()
278     if fields not in _record_types:
279         class _Record(object):
280             __slots__ = fields
281             def __repr__(self):
282                 return repr(dict(self))
283             def __getitem__(self, key):
284                 return getattr(self, key)
285             def __setitem__(self, key, value):
286                 setattr(self, key, value)
287             #def __iter__(self):
288             #    for field in self.__slots__:
289             #        yield field, getattr(self, field)
290             def keys(self):
291                 return self.__slots__
292             def __eq__(self, other):
293                 if isinstance(other, dict):
294                     return dict(self) == other
295                 elif isinstance(other, _Record):
296                     return all(self[k] == other[k] for k in self.keys())
297                 raise TypeError()
298             def __ne__(self, other):
299                 return not (self == other)
300         _record_types[fields] = _Record
301     return _record_types[fields]()
302
303 class ComposedType(Type):
304     def __init__(self, fields):
305         self.fields = tuple(fields)
306     
307     def read(self, file):
308         item = get_record(k for k, v in self.fields)
309         for key, type_ in self.fields:
310             item[key], file = type_.read(file)
311         return item, file
312     
313     def write(self, file, item):
314         for key, type_ in self.fields:
315             file = type_.write(file, item[key])
316         return file
317
318 class ChecksummedType(Type):
319     def __init__(self, inner):
320         self.inner = inner
321     
322     def read(self, file):
323         obj, file = self.inner.read(file)
324         data = self.inner.pack(obj)
325         
326         checksum, file = read(file, 4)
327         if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
328             raise ValueError('invalid checksum')
329         
330         return obj, file
331     
332     def write(self, file, item):
333         data = self.inner.pack(item)
334         return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
335
336 class FloatingInteger(object):
337     __slots__ = ['bits', '_target']
338     
339     @classmethod
340     def from_target_upper_bound(cls, target):
341         n = bases.natural_to_string(target)
342         if n and ord(n[0]) >= 128:
343             n = '\x00' + n
344         bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
345         bits = struct.unpack('<I', bits2)[0]
346         return cls(bits)
347     
348     def __init__(self, bits, target=None):
349         self.bits = bits
350         self._target = None
351         if target is not None and self.target != target:
352             raise ValueError('target does not match')
353     
354     @property
355     def target(self):
356         res = self._target
357         if res is None:
358             res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
359         return res
360     
361     def __hash__(self):
362         return hash(self.bits)
363     
364     def __eq__(self, other):
365         return self.bits == other.bits
366     
367     def __ne__(self, other):
368         return not (self == other)
369     
370     def __cmp__(self, other):
371         assert False
372     
373     def __repr__(self):
374         return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
375
376 class FloatingIntegerType(Type):
377     _inner = StructType('<I')
378     
379     def read(self, file):
380         bits, file = self._inner.read(file)
381         return FloatingInteger(bits), file
382     
383     def write(self, file, item):
384         return self._inner.write(file, item.bits)
385
386 class PossiblyNoneType(Type):
387     def __init__(self, none_value, inner):
388         self.none_value = none_value
389         self.inner = inner
390     
391     def read(self, file):
392         value, file = self.inner.read(file)
393         return None if value == self.none_value else value, file
394     
395     def write(self, file, item):
396         if item == self.none_value:
397             raise ValueError('none_value used')
398         return self.inner.write(file, self.none_value if item is None else item)
399
400 address_type = ComposedType([
401     ('services', StructType('<Q')),
402     ('address', IPV6AddressType()),
403     ('port', StructType('>H')),
404 ])
405
406 tx_type = ComposedType([
407     ('version', StructType('<I')),
408     ('tx_ins', ListType(ComposedType([
409         ('previous_output', PossiblyNoneType(slush.frozendict(hash=0, index=2**32 - 1), ComposedType([
410             ('hash', HashType()),
411             ('index', StructType('<I')),
412         ]))),
413         ('script', VarStrType()),
414         ('sequence', PossiblyNoneType(2**32 - 1, StructType('<I'))),
415     ]))),
416     ('tx_outs', ListType(ComposedType([
417         ('value', StructType('<Q')),
418         ('script', VarStrType()),
419     ]))),
420     ('lock_time', StructType('<I')),
421 ])
422
423 merkle_branch_type = ListType(HashType())
424
425 merkle_tx_type = ComposedType([
426     ('tx', tx_type),
427     ('block_hash', HashType()),
428     ('merkle_branch', merkle_branch_type),
429     ('index', StructType('<i')),
430 ])
431
432 block_header_type = ComposedType([
433     ('version', StructType('<I')),
434     ('previous_block', PossiblyNoneType(0, HashType())),
435     ('merkle_root', HashType()),
436     ('timestamp', StructType('<I')),
437     ('bits', FloatingIntegerType()),
438     ('nonce', StructType('<I')),
439 ])
440
441 block_type = ComposedType([
442     ('header', block_header_type),
443     ('txs', ListType(tx_type)),
444 ])
445
446 aux_pow_type = ComposedType([
447     ('merkle_tx', merkle_tx_type),
448     ('merkle_branch', merkle_branch_type),
449     ('index', StructType('<i')),
450     ('parent_block_header', block_header_type),
451 ])
452
453
454 merkle_record_type = ComposedType([
455     ('left', HashType()),
456     ('right', HashType()),
457 ])
458
459 def merkle_hash(hashes):
460     if not hashes:
461         return 0
462     hash_list = list(hashes)
463     while len(hash_list) > 1:
464         hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
465             for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
466     return hash_list[0]
467
468 def calculate_merkle_branch(hashes, index):
469     # XXX optimize this
470     
471     hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
472     
473     while len(hash_list) > 1:
474         hash_list = [
475             (
476                 merkle_record_type.hash256(dict(left=left, right=right)),
477                 left_f or right_f,
478                 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
479             )
480             for (left, left_f, left_l), (right, right_f, right_l) in
481                 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
482         ]
483     
484     res = [x['hash'] for x in hash_list[0][2]]
485     
486     assert hash_list[0][1]
487     assert check_merkle_branch(hashes[index], index, res) == hash_list[0][0]
488     assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
489     
490     return res
491
492 def check_merkle_branch(tip_hash, index, merkle_branch):
493     return reduce(lambda c, (i, h): merkle_record_type.hash256(
494         dict(left=h, right=c) if 2**i & index else
495         dict(left=c, right=h)
496     ), enumerate(merkle_branch), tip_hash)
497
498 def target_to_average_attempts(target):
499     return 2**256//(target + 1)
500
501 def target_to_difficulty(target):
502     return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
503
504 # tx
505
506 def tx_get_sigop_count(tx):
507     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'])
508
509 # human addresses
510
511 human_address_type = ChecksummedType(ComposedType([
512     ('version', StructType('<B')),
513     ('pubkey_hash', ShortHashType()),
514 ]))
515
516 pubkey_type = PassthruType()
517
518 def pubkey_hash_to_address(pubkey_hash, net):
519     return human_address_type.pack_base58(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash))
520
521 def pubkey_to_address(pubkey, net):
522     return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
523
524 def address_to_pubkey_hash(address, net):
525     x = human_address_type.unpack_base58(address)
526     if x['version'] != net.ADDRESS_VERSION:
527         raise ValueError('address not for this net!')
528     return x['pubkey_hash']
529
530 # transactions
531
532 def pubkey_to_script2(pubkey):
533     return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
534
535 def pubkey_hash_to_script2(pubkey_hash):
536     return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
537
538 def script2_to_address(script2, net):
539     try:
540         pubkey = script2[1:-1]
541         script2_test = pubkey_to_script2(pubkey)
542     except:
543         pass
544     else:
545         if script2_test == script2:
546             return pubkey_to_address(pubkey, net)
547     
548     try:
549         pubkey_hash = ShortHashType().unpack(script2[3:-2])
550         script2_test2 = pubkey_hash_to_script2(pubkey_hash)
551     except:
552         pass
553     else:
554         if script2_test2 == script2:
555             return pubkey_hash_to_address(pubkey_hash, net)
556
557 def script2_to_human(script2, net):
558     try:
559         pubkey = script2[1:-1]
560         script2_test = pubkey_to_script2(pubkey)
561     except:
562         pass
563     else:
564         if script2_test == script2:
565             return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
566     
567     try:
568         pubkey_hash = ShortHashType().unpack(script2[3:-2])
569         script2_test2 = pubkey_hash_to_script2(pubkey_hash)
570     except:
571         pass
572     else:
573         if script2_test2 == script2:
574             return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
575     
576     return 'Unknown. Script: %s'  % (script2.encode('hex'),)