1 from __future__ import division
8 from p2pool.util import bases, math
11 class EarlyEnd(Exception):
14 class LateEnd(Exception):
17 def read((data, pos), length):
18 data2 = data[pos:pos + length]
19 if len(data2) != length:
21 return data2, (data, pos + length)
23 def size((data, pos)):
24 return len(data) - pos
29 # the same data can have only one unpacked representation, but multiple packed binary representations
32 rval = getattr(self, '_hash', None)
35 rval = self._hash = hash((type(self), frozenset(self.__dict__.items())))
41 def __eq__(self, other):
42 return type(other) is type(self) and other.__dict__ == self.__dict__
44 def __ne__(self, other):
45 return not (self == other)
47 def _unpack(self, data):
48 obj, (data2, pos) = self.read((data, 0))
58 f = self.write(None, obj)
68 def unpack(self, data):
69 obj = self._unpack(data)
72 data2 = self._pack(obj)
74 if self._unpack(data2) != obj:
75 raise AssertionError()
80 data = self._pack(obj)
83 if self._unpack(data) != obj:
84 raise AssertionError((self._unpack(data), obj))
89 def pack_base58(self, obj):
90 return base58.encode(self.pack(obj))
92 def unpack_base58(self, base58_data):
93 return self.unpack(base58.decode(base58_data))
96 def hash160(self, obj):
97 return IntType(160).unpack(hashlib.new('ripemd160', hashlib.sha256(self.pack(obj)).digest()).digest())
99 def hash256(self, obj):
100 return IntType(256).unpack(hashlib.sha256(hashlib.sha256(self.pack(obj)).digest()).digest())
102 def scrypt(self, obj):
104 return IntType(256).unpack(ltc_scrypt.getPoWHash(self.pack(obj)))
106 class VarIntType(Type):
107 # redundancy doesn't matter here because bitcoin and p2pool both reencode before hashing
108 def read(self, file):
109 data, file = read(file, 1)
114 desc, length = '<H', 2
116 desc, length = '<I', 4
118 desc, length = '<Q', 8
120 raise AssertionError()
121 data, file = read(file, length)
122 return struct.unpack(desc, data)[0], file
124 def write(self, file, item):
126 file = file, struct.pack('<B', item)
128 file = file, struct.pack('<BH', 0xfd, item)
129 elif item <= 0xffffffff:
130 file = file, struct.pack('<BI', 0xfe, item)
131 elif item <= 0xffffffffffffffff:
132 file = file, struct.pack('<BQ', 0xff, item)
134 raise ValueError('int too large for varint')
137 class VarStrType(Type):
138 _inner_size = VarIntType()
140 def read(self, file):
141 length, file = self._inner_size.read(file)
142 return read(file, length)
144 def write(self, file, item):
145 return self._inner_size.write(file, len(item)), item
147 class PassthruType(Type):
148 def read(self, file):
149 return read(file, size(file))
151 def write(self, file, item):
154 class EnumType(Type):
155 def __init__(self, inner, values):
160 for k, v in values.iteritems():
162 raise ValueError('duplicate value in values')
166 def read(self, file):
167 data, file = self.inner.read(file)
168 if data not in self.keys:
169 raise ValueError('enum data (%r) not in values (%r)' % (data, self.values))
170 return self.keys[data], file
172 def write(self, file, item):
173 if item not in self.values:
174 raise ValueError('enum item (%r) not in values (%r)' % (item, self.values))
175 return self.inner.write(file, self.values[item])
177 class ListType(Type):
178 _inner_size = VarIntType()
180 def __init__(self, type):
183 def read(self, file):
184 length, file = self._inner_size.read(file)
186 for i in xrange(length):
187 item, file = self.type.read(file)
191 def write(self, file, item):
192 file = self._inner_size.write(file, len(item))
194 file = self.type.write(file, subitem)
197 class StructType(Type):
198 __slots__ = 'desc length'.split(' ')
200 def __init__(self, desc):
202 self.length = struct.calcsize(self.desc)
204 def read(self, file):
205 data, file = read(file, self.length)
206 return struct.unpack(self.desc, data)[0], file
208 def write(self, file, item):
209 return file, struct.pack(self.desc, item)
212 __slots__ = 'bytes step format_str max'.split(' ')
214 def __new__(cls, bits, endianness='little'):
216 assert endianness in ['little', 'big']
217 if bits in [8, 16, 32, 64]:
218 return StructType(('<' if endianness == 'little' else '>') + {8: 'B', 16: 'H', 32: 'I', 64: 'Q'}[bits])
220 return object.__new__(cls, bits, endianness)
222 def __init__(self, bits, endianness='little'):
224 assert endianness in ['little', 'big']
226 self.step = -1 if endianness == 'little' else 1
227 self.format_str = '%%0%ix' % (2*self.bytes)
230 def read(self, file, b2a_hex=binascii.b2a_hex):
231 data, file = read(file, self.bytes)
232 return int(b2a_hex(data[::self.step]), 16), file
234 def write(self, file, item, a2b_hex=binascii.a2b_hex):
235 if not 0 <= item < self.max:
236 raise ValueError('invalid int value - %r' % (item,))
237 return file, a2b_hex(self.format_str % (item,))[::self.step]
239 class IPV6AddressType(Type):
240 def read(self, file):
241 data, file = read(file, 16)
242 if data[:12] != '00000000000000000000ffff'.decode('hex'):
243 raise ValueError('ipv6 addresses not supported yet')
244 return '.'.join(str(ord(x)) for x in data[12:]), file
246 def write(self, file, item):
247 bits = map(int, item.split('.'))
249 raise ValueError('invalid address: %r' % (bits,))
250 data = '00000000000000000000ffff'.decode('hex') + ''.join(chr(x) for x in bits)
251 assert len(data) == 16, len(data)
256 def get_record(fields):
257 fields = tuple(sorted(fields))
260 if fields not in _record_types:
261 class _Record(object):
264 return repr(dict(self))
265 def __getitem__(self, key):
266 return getattr(self, key)
267 def __setitem__(self, key, value):
268 setattr(self, key, value)
270 # for field in self.__slots__:
271 # yield field, getattr(self, field)
273 return self.__slots__
274 def __eq__(self, other):
275 if isinstance(other, dict):
276 return dict(self) == other
277 elif isinstance(other, _Record):
278 return all(self[k] == other[k] for k in self.keys())
280 def __ne__(self, other):
281 return not (self == other)
282 _record_types[fields] = _Record
283 return _record_types[fields]()
285 class ComposedType(Type):
286 def __init__(self, fields):
287 self.fields = tuple(fields)
289 def read(self, file):
290 item = get_record(k for k, v in self.fields)
291 for key, type_ in self.fields:
292 item[key], file = type_.read(file)
295 def write(self, file, item):
296 for key, type_ in self.fields:
297 file = type_.write(file, item[key])
300 class ChecksummedType(Type):
301 def __init__(self, inner):
304 def read(self, file):
305 obj, file = self.inner.read(file)
306 data = self.inner.pack(obj)
308 checksum, file = read(file, 4)
309 if checksum != hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]:
310 raise ValueError('invalid checksum')
314 def write(self, file, item):
315 data = self.inner.pack(item)
316 return (file, data), hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]
318 class FloatingInteger(object):
319 __slots__ = ['bits', '_target']
322 def from_target_upper_bound(cls, target):
323 n = bases.natural_to_string(target)
324 if n and ord(n[0]) >= 128:
326 bits2 = (chr(len(n)) + (n + 3*chr(0))[:3])[::-1]
327 bits = struct.unpack('<I', bits2)[0]
330 def __init__(self, bits, target=None):
333 if target is not None and self.target != target:
334 raise ValueError('target does not match')
340 res = self._target = math.shift_left(self.bits & 0x00ffffff, 8 * ((self.bits >> 24) - 3))
344 return hash(self.bits)
346 def __eq__(self, other):
347 return self.bits == other.bits
349 def __ne__(self, other):
350 return not (self == other)
352 def __cmp__(self, other):
356 return 'FloatingInteger(bits=%s, target=%s)' % (hex(self.bits), hex(self.target))
358 class FloatingIntegerType(Type):
361 def read(self, file):
362 bits, file = self._inner.read(file)
363 return FloatingInteger(bits), file
365 def write(self, file, item):
366 return self._inner.write(file, item.bits)
368 class PossiblyNoneType(Type):
369 def __init__(self, none_value, inner):
370 self.none_value = none_value
373 def read(self, file):
374 value, file = self.inner.read(file)
375 return None if value == self.none_value else value, file
377 def write(self, file, item):
378 if item == self.none_value:
379 raise ValueError('none_value used')
380 return self.inner.write(file, self.none_value if item is None else item)
382 address_type = ComposedType([
383 ('services', IntType(64)),
384 ('address', IPV6AddressType()),
385 ('port', IntType(16, 'big')),
388 tx_type = ComposedType([
389 ('version', IntType(32)),
390 ('tx_ins', ListType(ComposedType([
391 ('previous_output', PossiblyNoneType(dict(hash=0, index=2**32 - 1), ComposedType([
392 ('hash', IntType(256)),
393 ('index', IntType(32)),
395 ('script', VarStrType()),
396 ('sequence', PossiblyNoneType(2**32 - 1, IntType(32))),
398 ('tx_outs', ListType(ComposedType([
399 ('value', IntType(64)),
400 ('script', VarStrType()),
402 ('lock_time', IntType(32)),
405 merkle_branch_type = ListType(IntType(256))
407 merkle_tx_type = ComposedType([
409 ('block_hash', IntType(256)),
410 ('merkle_branch', merkle_branch_type),
411 ('index', IntType(32)),
414 block_header_type = ComposedType([
415 ('version', IntType(32)),
416 ('previous_block', PossiblyNoneType(0, IntType(256))),
417 ('merkle_root', IntType(256)),
418 ('timestamp', IntType(32)),
419 ('bits', FloatingIntegerType()),
420 ('nonce', IntType(32)),
423 block_type = ComposedType([
424 ('header', block_header_type),
425 ('txs', ListType(tx_type)),
428 aux_pow_type = ComposedType([
429 ('merkle_tx', merkle_tx_type),
430 ('merkle_branch', merkle_branch_type),
431 ('index', IntType(32)),
432 ('parent_block_header', block_header_type),
436 merkle_record_type = ComposedType([
437 ('left', IntType(256)),
438 ('right', IntType(256)),
441 def merkle_hash(hashes):
444 hash_list = list(hashes)
445 while len(hash_list) > 1:
446 hash_list = [merkle_record_type.hash256(dict(left=left, right=left if right is None else right))
447 for left, right in zip(hash_list[::2], hash_list[1::2] + [None])]
450 def calculate_merkle_branch(hashes, index):
453 hash_list = [(h, i == index, []) for i, h in enumerate(hashes)]
455 while len(hash_list) > 1:
458 merkle_record_type.hash256(dict(left=left, right=right)),
460 (left_l if left_f else right_l) + [dict(side=1, hash=right) if left_f else dict(side=0, hash=left)],
462 for (left, left_f, left_l), (right, right_f, right_l) in
463 zip(hash_list[::2], hash_list[1::2] + [hash_list[::2][-1]])
466 res = [x['hash'] for x in hash_list[0][2]]
468 assert hash_list[0][1]
469 assert check_merkle_branch(hashes[index], index, res) == hash_list[0][0]
470 assert index == sum(k*2**i for i, k in enumerate([1-x['side'] for x in hash_list[0][2]]))
474 def check_merkle_branch(tip_hash, index, merkle_branch):
475 return reduce(lambda c, (i, h): merkle_record_type.hash256(
476 dict(left=h, right=c) if 2**i & index else
477 dict(left=c, right=h)
478 ), enumerate(merkle_branch), tip_hash)
480 def target_to_average_attempts(target):
481 return 2**256//(target + 1)
483 def target_to_difficulty(target):
484 return (0xffff0000 * 2**(256-64) + 1)/(target + 1)
488 def tx_get_sigop_count(tx):
489 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'])
493 human_address_type = ChecksummedType(ComposedType([
494 ('version', IntType(8)),
495 ('pubkey_hash', IntType(160)),
498 pubkey_type = PassthruType()
500 def pubkey_hash_to_address(pubkey_hash, net):
501 return human_address_type.pack_base58(dict(version=net.ADDRESS_VERSION, pubkey_hash=pubkey_hash))
503 def pubkey_to_address(pubkey, net):
504 return pubkey_hash_to_address(pubkey_type.hash160(pubkey), net)
506 def address_to_pubkey_hash(address, net):
507 x = human_address_type.unpack_base58(address)
508 if x['version'] != net.ADDRESS_VERSION:
509 raise ValueError('address not for this net!')
510 return x['pubkey_hash']
514 def pubkey_to_script2(pubkey):
515 return ('\x41' + pubkey_type.pack(pubkey)) + '\xac'
517 def pubkey_hash_to_script2(pubkey_hash):
518 return '\x76\xa9' + ('\x14' + IntType(160).pack(pubkey_hash)) + '\x88\xac'
520 def script2_to_address(script2, net):
522 pubkey = script2[1:-1]
523 script2_test = pubkey_to_script2(pubkey)
527 if script2_test == script2:
528 return pubkey_to_address(pubkey, net)
531 pubkey_hash = IntType(160).unpack(script2[3:-2])
532 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
536 if script2_test2 == script2:
537 return pubkey_hash_to_address(pubkey_hash, net)
539 def script2_to_human(script2, net):
541 pubkey = script2[1:-1]
542 script2_test = pubkey_to_script2(pubkey)
546 if script2_test == script2:
547 return 'Pubkey. Address: %s' % (pubkey_to_address(pubkey, net),)
550 pubkey_hash = IntType(160).unpack(script2[3:-2])
551 script2_test2 = pubkey_hash_to_script2(pubkey_hash)
555 if script2_test2 == script2:
556 return 'Address. Address: %s' % (pubkey_hash_to_address(pubkey_hash, net),)
558 return 'Unknown. Script: %s' % (script2.encode('hex'),)