1 from __future__ import division
7 from p2pool.util import bases, math, expiring_dict, memoize, slush
10 class EarlyEnd(Exception):
13 class LateEnd(Exception):
16 def read((data, pos), length):
17 data2 = data[pos:pos + length]
18 if len(data2) != length:
20 return data2, (data, pos + length)
22 def size((data, pos)):
23 return len(data) - pos
26 # the same data can have only one unpacked representation, but multiple packed binary representations
29 rval = getattr(self, '_hash', None)
32 rval = self._hash = hash((type(self), frozenset(self.__dict__.items())))
38 def __eq__(self, other):
39 return type(other) is type(self) and other.__dict__ == self.__dict__
41 def __ne__(self, other):
42 return not (self == other)
44 def _unpack(self, data):
45 obj, (data2, pos) = self.read((data, 0))
55 f = self.write(None, obj)
65 def unpack(self, data):
66 obj = self._unpack(data)
69 data2 = self._pack(obj)
71 if self._unpack(data2) != obj:
72 raise AssertionError()
77 data = self._pack(obj)
80 if self._unpack(data) != obj:
81 raise AssertionError((self._unpack(data), obj))
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
97 def disable_caching(cls):
98 assert cls._backing is not None
101 cls.pack2 = cls._pre_pack2
103 cls.unpack = cls._pre_unpack
107 return self.pack2(slush.immutify(obj))
110 def pack_base58(self, obj):
111 return base58.encode(self.pack(obj))
113 def unpack_base58(self, base58_data):
114 return self.unpack(base58.decode(base58_data))
117 def hash160(self, obj):
118 return ShortHashType().unpack(hashlib.new('ripemd160', hashlib.sha256(self.pack(obj)).digest()).digest())
120 def hash256(self, obj):
121 return HashType().unpack(hashlib.sha256(hashlib.sha256(self.pack(obj)).digest()).digest())
123 def scrypt(self, obj):
125 return HashType().unpack(ltc_scrypt.getPoWHash(self.pack(obj)))
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)
135 desc, length = '<H', 2
137 desc, length = '<I', 4
139 desc, length = '<Q', 8
141 raise AssertionError()
142 data, file = read(file, length)
143 return struct.unpack(desc, data)[0], file
145 def write(self, file, item):
147 file = file, struct.pack('<B', item)
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)
155 raise ValueError('int too large for varint')
158 class VarStrType(Type):
159 _inner_size = VarIntType()
161 def read(self, file):
162 length, file = self._inner_size.read(file)
163 return read(file, length)
165 def write(self, file, item):
166 return self._inner_size.write(file, len(item)), item
168 class FixedStrType(Type):
169 def __init__(self, length):
172 def read(self, file):
173 return read(file, self.length)
175 def write(self, file, item):
176 if len(item) != self.length:
177 raise ValueError('incorrect length item!')
180 class EnumType(Type):
181 def __init__(self, inner, values):
183 self.values = slush.frozendict(values)
186 for k, v in values.iteritems():
188 raise ValueError('duplicate value in values')
190 self.keys = slush.frozendict(keys)
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
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])
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
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]
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
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]
225 class ListType(Type):
226 _inner_size = VarIntType()
228 def __init__(self, type):
231 def read(self, file):
232 length, file = self._inner_size.read(file)
234 for i in xrange(length):
235 item, file = self.type.read(file)
239 def write(self, file, item):
240 file = self._inner_size.write(file, len(item))
242 file = self.type.write(file, subitem)
245 class StructType(Type):
246 def __init__(self, desc):
248 self.length = struct.calcsize(self.desc)
250 def read(self, file):
251 data, file = read(file, self.length)
252 res, = struct.unpack(self.desc, data)
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,))
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
269 def write(self, file, item):
270 bits = map(int, item.split('.'))
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)
279 def get_record(fields):
280 fields = tuple(sorted(fields))
283 if fields not in _record_types:
284 class _Record(object):
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)
293 # for field in self.__slots__:
294 # yield field, getattr(self, field)
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())
303 def __ne__(self, other):
304 return not (self == other)
305 _record_types[fields] = _Record
306 return _record_types[fields]()
308 class ComposedType(Type):
309 def __init__(self, fields):
310 self.fields = tuple(fields)
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)
318 def write(self, file, item):
319 for key, type_ in self.fields:
320 file = type_.write(file, item[key])
323 class ChecksummedType(Type):
324 def __init__(self, inner):
327 def read(self, file):
328 obj, file = self.inner.read(file)
329 data = self.inner.pack(obj)
331 checksum, file = read(file, 4)
332 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
333 raise ValueError('invalid checksum')
337 def write(self, file, item):
338 data = self.inner.pack(item)
339 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
341 class FloatingInteger(object):
342 __slots__ = ['bits', '_target']
345 def from_target_upper_bound(cls, target):
346 n = bases.natural_to_string(target)
347 if n and ord(n[0]) >= 128:
349 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
350 bits = struct.unpack('<I', bits2)[0]
353 def __init__(self, bits, target=None):
356 if target is not None and self.target != target:
357 raise ValueError('target does not match')
363 res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
367 return hash(self.bits)
369 def __eq__(self, other):
370 return self.bits == other.bits
372 def __ne__(self, other):
373 return not (self == other)
375 def __cmp__(self, other):
379 return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
381 class FloatingIntegerType(Type):
382 _inner = StructType('<I')
384 def read(self, file):
385 bits, file = self._inner.read(file)
386 return FloatingInteger(bits), file
388 def write(self, file, item):
389 return self._inner.write(file, item.bits)
391 class PossiblyNoneType(Type):
392 def __init__(self, none_value, inner):
393 self.none_value = none_value
396 def read(self, file):
397 value, file = self.inner.read(file)
398 return None if value == self.none_value else value, file
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)
405 address_type = ComposedType([
406 ('services', StructType('<Q')),
407 ('address', IPV6AddressType()),
408 ('port', StructType('>H')),
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')),
418 ('script', VarStrType()),
419 ('sequence', PossiblyNoneType(2**32 - 1, StructType('<I'))),
421 ('tx_outs', ListType(ComposedType([
422 ('value', StructType('<Q')),
423 ('script', VarStrType()),
425 ('lock_time', StructType('<I')),
428 merkle_branch_type = ListType(HashType())
430 merkle_tx_type = ComposedType([
432 ('block_hash', HashType()),
433 ('merkle_branch', merkle_branch_type),
434 ('index', StructType('<i')),
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')),
446 block_type = ComposedType([
447 ('header', block_header_type),
448 ('txs', ListType(tx_type)),
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),
459 merkle_record_type = ComposedType([
460 ('left', HashType()),
461 ('right', HashType()),
464 def merkle_hash(hashes):
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])]
473 def calculate_merkle_branch(hashes, index):
476 hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
478 while len(hash_list) > 1:
481 merkle_record_type.hash256(dict(left=left, right=right)),
483 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
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]])
489 res = [x['hash'] for x in hash_list[0][2]]
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]]))
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)
503 def target_to_average_attempts(target):
504 return 2**256//(target + 1)
506 def target_to_difficulty(target):
507 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
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'])
516 human_address_type = ChecksummedType(ComposedType([
517 ('version', StructType('<B')),
518 ('pubkey_hash', ShortHashType()),
521 pubkey_type = FixedStrType(65)
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))
526 def pubkey_to_address(pubkey, net):
527 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
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']
537 def pubkey_to_script2(pubkey):
538 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
540 def pubkey_hash_to_script2(pubkey_hash):
541 return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
543 def script2_to_address(script2, net):
545 pubkey = script2[1:-1]
546 script2_test = pubkey_to_script2(pubkey)
550 if script2_test == script2:
551 return pubkey_to_address(pubkey, net)
554 pubkey_hash = ShortHashType().unpack(script2[3:-2])
555 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
559 if script2_test2 == script2:
560 return pubkey_hash_to_address(pubkey_hash, net)
562 def script2_to_human(script2, net):
564 pubkey = script2[1:-1]
565 script2_test = pubkey_to_script2(pubkey)
569 if script2_test == script2:
570 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
573 pubkey_hash = ShortHashType().unpack(script2[3:-2])
574 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
578 if script2_test2 == script2:
579 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
581 return 'Unknown. Script: %s' % (script2.encode('hex'),)