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 PassthruType(Type):
181 def read(self, file):
182 return read(file, size(file))
184 def write(self, file, item):
187 class EnumType(Type):
188 def __init__(self, inner, values):
190 self.values = slush.frozendict(values)
193 for k, v in values.iteritems():
195 raise ValueError('duplicate value in values')
197 self.keys = slush.frozendict(keys)
199 def read(self, file):
200 data, file = self.inner.read(file)
201 if data not in self.keys:
202 raise ValueError('enum data (%r) not in values (%r)' % (data, self.values))
203 return self.keys[data], file
205 def write(self, file, item):
206 if item not in self.values:
207 raise ValueError('enum item (%r) not in values (%r)' % (item, self.values))
208 return self.inner.write(file, self.values[item])
210 class HashType(Type):
211 def read(self, file):
212 data, file = read(file, 256//8)
213 return int(data[::-1].encode('hex'), 16), file
215 def write(self, file, item):
216 if not 0 <= item < 2**256:
217 raise ValueError('invalid hash value - %r' % (item,))
218 if item != 0 and item < 2**160:
219 print 'Very low hash value - maybe you meant to use ShortHashType? %x' % (item,)
220 return file, ('%064x' % (item,)).decode('hex')[::-1]
222 class ShortHashType(Type):
223 def read(self, file):
224 data, file = read(file, 160//8)
225 return int(data[::-1].encode('hex'), 16), file
227 def write(self, file, item):
228 if not 0 <= item < 2**160:
229 raise ValueError('invalid hash value - %r' % (item,))
230 return file, ('%040x' % (item,)).decode('hex')[::-1]
232 class ListType(Type):
233 _inner_size = VarIntType()
235 def __init__(self, type):
238 def read(self, file):
239 length, file = self._inner_size.read(file)
241 for i in xrange(length):
242 item, file = self.type.read(file)
246 def write(self, file, item):
247 file = self._inner_size.write(file, len(item))
249 file = self.type.write(file, subitem)
252 class StructType(Type):
253 def __init__(self, desc):
255 self.length = struct.calcsize(self.desc)
257 def read(self, file):
258 data, file = read(file, self.length)
259 res, = struct.unpack(self.desc, data)
262 def write(self, file, item):
263 data = struct.pack(self.desc, item)
264 if struct.unpack(self.desc, data)[0] != item:
265 # special test because struct doesn't error on some overflows
266 raise ValueError('''item didn't survive pack cycle (%r)''' % (item,))
269 class IPV6AddressType(Type):
270 def read(self, file):
271 data, file = read(file, 16)
272 if data[:12] != '00000000000000000000ffff'.decode('hex'):
273 raise ValueError('ipv6 addresses not supported yet')
274 return '.'.join(str(ord(x)) for x in data[12:]), file
276 def write(self, file, item):
277 bits = map(int, item.split('.'))
279 raise ValueError('invalid address: %r' % (bits,))
280 data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
281 assert len(data) == 16, len(data)
286 def get_record(fields):
287 fields = tuple(sorted(fields))
290 if fields not in _record_types:
291 class _Record(object):
294 return repr(dict(self))
295 def __getitem__(self, key):
296 return getattr(self, key)
297 def __setitem__(self, key, value):
298 setattr(self, key, value)
300 # for field in self.__slots__:
301 # yield field, getattr(self, field)
303 return self.__slots__
304 def __eq__(self, other):
305 if isinstance(other, dict):
306 return dict(self) == other
307 elif isinstance(other, _Record):
308 return all(self[k] == other[k] for k in self.keys())
310 def __ne__(self, other):
311 return not (self == other)
312 _record_types[fields] = _Record
313 return _record_types[fields]()
315 class ComposedType(Type):
316 def __init__(self, fields):
317 self.fields = tuple(fields)
319 def read(self, file):
320 item = get_record(k for k, v in self.fields)
321 for key, type_ in self.fields:
322 item[key], file = type_.read(file)
325 def write(self, file, item):
326 for key, type_ in self.fields:
327 file = type_.write(file, item[key])
330 class ChecksummedType(Type):
331 def __init__(self, inner):
334 def read(self, file):
335 obj, file = self.inner.read(file)
336 data = self.inner.pack(obj)
338 checksum, file = read(file, 4)
339 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
340 raise ValueError('invalid checksum')
344 def write(self, file, item):
345 data = self.inner.pack(item)
346 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
348 class FloatingInteger(object):
349 __slots__ = ['bits', '_target']
352 def from_target_upper_bound(cls, target):
353 n = bases.natural_to_string(target)
354 if n and ord(n[0]) >= 128:
356 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
357 bits = struct.unpack('<I', bits2)[0]
360 def __init__(self, bits, target=None):
363 if target is not None and self.target != target:
364 raise ValueError('target does not match')
370 res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
374 return hash(self.bits)
376 def __eq__(self, other):
377 return self.bits == other.bits
379 def __ne__(self, other):
380 return not (self == other)
382 def __cmp__(self, other):
386 return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
388 class FloatingIntegerType(Type):
389 _inner = StructType('<I')
391 def read(self, file):
392 bits, file = self._inner.read(file)
393 return FloatingInteger(bits), file
395 def write(self, file, item):
396 return self._inner.write(file, item.bits)
398 class PossiblyNoneType(Type):
399 def __init__(self, none_value, inner):
400 self.none_value = none_value
403 def read(self, file):
404 value, file = self.inner.read(file)
405 return None if value == self.none_value else value, file
407 def write(self, file, item):
408 if item == self.none_value:
409 raise ValueError('none_value used')
410 return self.inner.write(file, self.none_value if item is None else item)
412 address_type = ComposedType([
413 ('services', StructType('<Q')),
414 ('address', IPV6AddressType()),
415 ('port', StructType('>H')),
418 tx_type = ComposedType([
419 ('version', StructType('<I')),
420 ('tx_ins', ListType(ComposedType([
421 ('previous_output', PossiblyNoneType(slush.frozendict(hash=0, index=2**32 - 1), ComposedType([
422 ('hash', HashType()),
423 ('index', StructType('<I')),
425 ('script', VarStrType()),
426 ('sequence', PossiblyNoneType(2**32 - 1, StructType('<I'))),
428 ('tx_outs', ListType(ComposedType([
429 ('value', StructType('<Q')),
430 ('script', VarStrType()),
432 ('lock_time', StructType('<I')),
435 merkle_branch_type = ListType(HashType())
437 merkle_tx_type = ComposedType([
439 ('block_hash', HashType()),
440 ('merkle_branch', merkle_branch_type),
441 ('index', StructType('<i')),
444 block_header_type = ComposedType([
445 ('version', StructType('<I')),
446 ('previous_block', PossiblyNoneType(0, HashType())),
447 ('merkle_root', HashType()),
448 ('timestamp', StructType('<I')),
449 ('bits', FloatingIntegerType()),
450 ('nonce', StructType('<I')),
453 block_type = ComposedType([
454 ('header', block_header_type),
455 ('txs', ListType(tx_type)),
458 aux_pow_type = ComposedType([
459 ('merkle_tx', merkle_tx_type),
460 ('merkle_branch', merkle_branch_type),
461 ('index', StructType('<i')),
462 ('parent_block_header', block_header_type),
466 merkle_record_type = ComposedType([
467 ('left', HashType()),
468 ('right', HashType()),
471 def merkle_hash(hashes):
474 hash_list = list(hashes)
475 while len(hash_list) > 1:
476 hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
477 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
480 def calculate_merkle_branch(hashes, index):
483 hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
485 while len(hash_list) > 1:
488 merkle_record_type.hash256(dict(left=left, right=right)),
490 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
492 for (left, left_f, left_l), (right, right_f, right_l) in
493 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
496 res = [x['hash'] for x in hash_list[0][2]]
498 assert hash_list[0][1]
499 assert check_merkle_branch(hashes[index], index, res) == hash_list[0][0]
500 assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
504 def check_merkle_branch(tip_hash, index, merkle_branch):
505 return reduce(lambda c, (i, h): merkle_record_type.hash256(
506 dict(left=h, right=c) if 2**i & index else
507 dict(left=c, right=h)
508 ), enumerate(merkle_branch), tip_hash)
510 def target_to_average_attempts(target):
511 return 2**256//(target + 1)
513 def target_to_difficulty(target):
514 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
518 def tx_get_sigop_count(tx):
519 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'])
523 human_address_type = ChecksummedType(ComposedType([
524 ('version', StructType('<B')),
525 ('pubkey_hash', ShortHashType()),
528 pubkey_type = PassthruType()
530 def pubkey_hash_to_address(pubkey_hash, net):
531 return human_address_type.pack_base58(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash))
533 def pubkey_to_address(pubkey, net):
534 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
536 def address_to_pubkey_hash(address, net):
537 x = human_address_type.unpack_base58(address)
538 if x['version'] != net.ADDRESS_VERSION:
539 raise ValueError('address not for this net!')
540 return x['pubkey_hash']
544 def pubkey_to_script2(pubkey):
545 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
547 def pubkey_hash_to_script2(pubkey_hash):
548 return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
550 def script2_to_address(script2, net):
552 pubkey = script2[1:-1]
553 script2_test = pubkey_to_script2(pubkey)
557 if script2_test == script2:
558 return pubkey_to_address(pubkey, net)
561 pubkey_hash = ShortHashType().unpack(script2[3:-2])
562 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
566 if script2_test2 == script2:
567 return pubkey_hash_to_address(pubkey_hash, net)
569 def script2_to_human(script2, net):
571 pubkey = script2[1:-1]
572 script2_test = pubkey_to_script2(pubkey)
576 if script2_test == script2:
577 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
580 pubkey_hash = ShortHashType().unpack(script2[3:-2])
581 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
585 if script2_test2 == script2:
586 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
588 return 'Unknown. Script: %s' % (script2.encode('hex'),)