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 PassthruType(Type):
169 def read(self, file):
170 return read(file, size(file))
172 def write(self, file, item):
175 class EnumType(Type):
176 def __init__(self, inner, values):
178 self.values = slush.frozendict(values)
181 for k, v in values.iteritems():
183 raise ValueError('duplicate value in values')
185 self.keys = slush.frozendict(keys)
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
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])
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
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]
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
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]
220 class ListType(Type):
221 _inner_size = VarIntType()
223 def __init__(self, type):
226 def read(self, file):
227 length, file = self._inner_size.read(file)
229 for i in xrange(length):
230 item, file = self.type.read(file)
234 def write(self, file, item):
235 file = self._inner_size.write(file, len(item))
237 file = self.type.write(file, subitem)
240 class StructType(Type):
241 def __init__(self, desc):
243 self.length = struct.calcsize(self.desc)
245 def read(self, file):
246 data, file = read(file, self.length)
247 res, = struct.unpack(self.desc, data)
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,))
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
264 def write(self, file, item):
265 bits = map(int, item.split('.'))
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)
274 def get_record(fields):
275 fields = tuple(sorted(fields))
278 if fields not in _record_types:
279 class _Record(object):
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)
288 # for field in self.__slots__:
289 # yield field, getattr(self, field)
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())
298 def __ne__(self, other):
299 return not (self == other)
300 _record_types[fields] = _Record
301 return _record_types[fields]()
303 class ComposedType(Type):
304 def __init__(self, fields):
305 self.fields = tuple(fields)
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)
313 def write(self, file, item):
314 for key, type_ in self.fields:
315 file = type_.write(file, item[key])
318 class ChecksummedType(Type):
319 def __init__(self, inner):
322 def read(self, file):
323 obj, file = self.inner.read(file)
324 data = self.inner.pack(obj)
326 checksum, file = read(file, 4)
327 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
328 raise ValueError('invalid checksum')
332 def write(self, file, item):
333 data = self.inner.pack(item)
334 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
336 class FloatingInteger(object):
337 __slots__ = ['bits', '_target']
340 def from_target_upper_bound(cls, target):
341 n = bases.natural_to_string(target)
342 if n and ord(n[0]) >= 128:
344 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
345 bits = struct.unpack('<I', bits2)[0]
348 def __init__(self, bits, target=None):
351 if target is not None and self.target != target:
352 raise ValueError('target does not match')
358 res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
362 return hash(self.bits)
364 def __eq__(self, other):
365 return self.bits == other.bits
367 def __ne__(self, other):
368 return not (self == other)
370 def __cmp__(self, other):
374 return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
376 class FloatingIntegerType(Type):
377 _inner = StructType('<I')
379 def read(self, file):
380 bits, file = self._inner.read(file)
381 return FloatingInteger(bits), file
383 def write(self, file, item):
384 return self._inner.write(file, item.bits)
386 class PossiblyNoneType(Type):
387 def __init__(self, none_value, inner):
388 self.none_value = none_value
391 def read(self, file):
392 value, file = self.inner.read(file)
393 return None if value == self.none_value else value, file
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)
400 address_type = ComposedType([
401 ('services', StructType('<Q')),
402 ('address', IPV6AddressType()),
403 ('port', StructType('>H')),
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')),
413 ('script', VarStrType()),
414 ('sequence', PossiblyNoneType(2**32 - 1, StructType('<I'))),
416 ('tx_outs', ListType(ComposedType([
417 ('value', StructType('<Q')),
418 ('script', VarStrType()),
420 ('lock_time', StructType('<I')),
423 merkle_branch_type = ListType(HashType())
425 merkle_tx_type = ComposedType([
427 ('block_hash', HashType()),
428 ('merkle_branch', merkle_branch_type),
429 ('index', StructType('<i')),
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')),
441 block_type = ComposedType([
442 ('header', block_header_type),
443 ('txs', ListType(tx_type)),
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),
454 merkle_record_type = ComposedType([
455 ('left', HashType()),
456 ('right', HashType()),
459 def merkle_hash(hashes):
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])]
468 def calculate_merkle_branch(hashes, index):
471 hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
473 while len(hash_list) > 1:
476 merkle_record_type.hash256(dict(left=left, right=right)),
478 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
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]])
484 res = [x['hash'] for x in hash_list[0][2]]
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]]))
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)
498 def target_to_average_attempts(target):
499 return 2**256//(target + 1)
501 def target_to_difficulty(target):
502 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
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'])
511 human_address_type = ChecksummedType(ComposedType([
512 ('version', StructType('<B')),
513 ('pubkey_hash', ShortHashType()),
516 pubkey_type = PassthruType()
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))
521 def pubkey_to_address(pubkey, net):
522 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
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']
532 def pubkey_to_script2(pubkey):
533 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
535 def pubkey_hash_to_script2(pubkey_hash):
536 return '\x76\xa9' + ('\x14' + ShortHashType().pack(pubkey_hash)) + '\x88\xac'
538 def script2_to_address(script2, net):
540 pubkey = script2[1:-1]
541 script2_test = pubkey_to_script2(pubkey)
545 if script2_test == script2:
546 return pubkey_to_address(pubkey, net)
549 pubkey_hash = ShortHashType().unpack(script2[3:-2])
550 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
554 if script2_test2 == script2:
555 return pubkey_hash_to_address(pubkey_hash, net)
557 def script2_to_human(script2, net):
559 pubkey = script2[1:-1]
560 script2_test = pubkey_to_script2(pubkey)
564 if script2_test == script2:
565 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
568 pubkey_hash = ShortHashType().unpack(script2[3:-2])
569 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
573 if script2_test2 == script2:
574 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
576 return 'Unknown. Script: %s' % (script2.encode('hex'),)